import datetime
import json
import re
import logging

from django.core.paginator import Paginator, EmptyPage
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from ihome.utils.fastdfs.fastdfs_storage import FastDFSStorage
from ihome.utils.views import housecount
from wangziye import models
from wangziye.models import House

logger = logging.getLogger('django')
class PushHouse(View):
    '''发布房源接口'''
    def post(self,request):
        '''添加房源'''
        #先判断用户是否登录
        if request.user.is_authenticated:

            # 1.请求参数
            dict = json.loads(request.body.decode())
            title = dict.get('title')
            price = dict.get('price')
            area_id = dict.get('area_id')
            address = dict.get('address')
            room_count = dict.get('room_count')
            acreage = dict.get('acreage')
            unit = dict.get('unit')
            capacity = dict.get('capacity')
            beds = dict.get('beds')
            deposit = dict.get('deposit')
            min_days = dict.get('min_days')
            max_days = dict.get('max_days')
            facility = dict.get('facility')
            print(price,deposit)

            # 2.校验参数(整体)
            if not all([title,price,area_id,address,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days,facility]):
                return JsonResponse({"errno": "4103",
                                     "errmsg": "缺少必传参数"})

            # 3.校验title参数
            if not re.match(r'^\w{1,20}$',title):
                return JsonResponse({'errno':'4103',
                                     'errmsg':'标题校验错误'})

            # 4.校验price参数
            if not re.match(r'[0-9]{1,10}$',price):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '价格校验错误'})

            # 5.校验城区id参数
            if not re.match(r'\w{1,10}$',area_id):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '价格校验错误'})

            # 6.校验房屋地址参数
            if not re.match(r'\w{1,20}$',address):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋地址校验错误'})

            # 7.校验房屋数目参数
            if not re.match(r'\d{1,10}$',room_count):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋数目校验错误'})

            # 8.校验房屋面积参数
            if not re.match(r'\d{1,10}$',acreage):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋面积校验错误'})

            # 9.校验房屋单元参数
            if not re.match(r'\w{1,10}$',unit):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋单元校验错误'})

            # 10.校验房屋容纳人数参数
            if not re.match(r'\d{1,2}$',capacity):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋容纳人数校验错误'})

            #11.检验房屋床铺配置参数
            if not re.match(r'\w{1,10}$',beds):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋床铺配置校验错误'})

            #12.检验房屋押金参数
            if not re.match(r'\d{1,10}$',deposit):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋押金校验错误'})

            #13.校验最少入住天数参数
            if not re.match(r'\d{1,10}$',min_days):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋入住最小天数校验错误'})

            #14.校验最大房屋入住天数参数
            if not re.match(r'\d{1,100}$',max_days):
                return JsonResponse({'errno': '4103',
                                     'errmsg': '房屋入住最大天数校验错误'})

            # #15.校验用户设施序号参数
            # if not re.match(r'\w{1,1000}$',facility):
            #     return JsonResponse({'errno': '4103',
            #                          'errmsg': '房屋设施校验错误'})

            # 用户已登录,操作写入数据库
            try:
                house = House.objects.create(user = request.user,
                                             title=title,
                                             price=int(price)*100,
                                             area_id=area_id,
                                             address=address,
                                             room_count=room_count,
                                             acreage=acreage,
                                             unit=unit,
                                             capacity=capacity,
                                             beds=beds,
                                             deposit=int(deposit)*100,
                                             min_days=min_days,
                                             max_days=max_days)
                house.facility.add(*facility)


            except Exception as e:
                logger.error(e)
                return JsonResponse({'errno':'4404',
                                     'errmsg':'数据保存错误'})


            return JsonResponse({
                                "errno": "0",
                                "errmsg": "发布成功",
                                "data": {
                                    "house_id": house.id
                                }
                            })
        else:
            # 用户未登录,提示他先登录,再添加信息

            return JsonResponse({'errno':'4104',
                                 'errmsg':'请先登录'})

    def index(self,request):
        current_page = request.GET.get('p')
        house_list = models.House.objects.all()
        paginator = Paginator(house_list, 4)
        try:
            posts = paginator.page(current_page)
        except Exception as e:
            posts = paginator.page(1)
        return render(request, 'search.html', {'posts': posts})







    def get(self,request):

        aid=request.GET.get('aid')
        aname=request.GET.get('aname')
        sd=request.GET.get('sd')
        ed=request.GET.get('ed')
        sk=request.GET.get('sk')
        page = request.GET.get('p')

        print(page)


        if not all([aid,sd,ed,sk,page]):
            return JsonResponse({'errno':4103,
                                 'errmsg':'传参错误'
                                })

        if sk=='new':
            orderby='-create_time'
        elif sk== 'booking':
            orderby='-order_count'
        elif sk== 'price-inc':
            orderby='price'
        elif sk== 'price-des':
            orderby='-price'

        else:
            return JsonResponse({
                'errno':'4103',
                'errmsg':'查询条件参数错误'
            })
        houses = House.objects.filter(area_id=aid).order_by(orderby)
        page_size = 3

        paginator = Paginator(houses, page_size)
        # 获取每页商品数据
        try:
            houses = paginator.page(page)
        except EmptyPage:
            # 如果page_num不正确，默认给用户400
            return JsonResponse({'code': 400,
                                 'errmsg': 'page数据出错'})
        # 获取列表页总页数
        total_page = paginator.num_pages


        try:
            start_date = datetime.datetime.strptime(sd, '%Y-%m-%d').date()
            end_date = datetime.datetime.strptime(ed, '%Y-%m-%d').date()

        except Exception as e:
            return JsonResponse({
                'errno': '4103',
                "errmsg": '时间参数错误'
            })


        houses_list = []
        fsdf = FastDFSStorage()
        for house in houses:
            num=housecount(house,start_date,end_date)
            if num >= house.room_count:
                continue
            houses_list.append({
                "address": house.address,
                "area_name": aname,
                "ctime": house.create_time.date(),
                "house_id": house.id,
                "img_url": fsdf.url(str(house.index_image_url)),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": fsdf.url(str(house.user.avatar)),


            })

        print(houses_list)




        return JsonResponse({

                "data": { "houses": houses_list,
                          "total_page":total_page

                        },"errmsg": "请求成功",
                          "errno": "0"

                        })







































